﻿

var obj = {
    financeTypeId: '',
    financeTypeNo: '',
    financeTypeName: '',
    financeTyperemark: '',
    office_id: '',
    user_id: '',
    createName: '',
    createTime: '',
    updateName: '',
    updateTime: '',
    isdelete:''
}

//新增弹框
layui.use('layer', function () {
    var $ = layui.$;
    var layer = layui.layer;
    var util = layui.util;
    var form = layui.form;
    var table = layui.table;


    // 事件
    util.on('lay-on', {
        'test-page-custom': function () {
            layer.open({
                type: 1,
                title: '新增类别',
                content: `
                      <form class="layui-form" action="">
          <div class="layui-form-item">
            <div class="layui-inline">
              <label class="layui-form-label">类别编号</label>
              <div class="layui-input-block">
                <input type="text" name="financeTypeNo" lay-verify="required" id="financeTypeNo" autocomplete="off" class="layui-input">
              </div>
            </div>
            <div class="layui-inline">
              <label class="layui-form-label">类别名称</label>
              <div class="layui-input-inline">
                    <input type="text" name="financeTypeName" lay-verify="required" id="financeTypeName" autocomplete="off" class="layui-input">
              </div>
            </div>
          </div>
          <div class="layui-form-item layui-form-text">
            <label class="layui-form-label">备注</label>
            <div class="layui-input-block">
                      <textarea placeholder="请输入内容" lay-verify="required" name="financeTyperemark" id="financeTyperemark" class="layui-textarea"></textarea>
            </div>
          </div>
          <div class="layui-form-item" style="text-align:center">
                <button class="layui-btn" lay-submit lay-filter="demo-login">确认</button>
            <button type="reset" class="layui-btn layui-btn-primary">取消</button>
          </div>
        </form>
                `,
                area: ['700px', '350px'],
                success: function () {

                    // 对弹层中的表单进行初始化渲染
                    form.render();
                    // 表单提交事件
                    form.on('submit(demo-login)', function (data) {

                        var field = data.field;

                        $.ajax({
                            url: '../Purchase/GetFinanceAdd',
                            type: 'post',
                            data: { data: JSON.stringify(field), token: localStorage.getItem("token") },
                            success: function (res) {
                                var s = JSON.parse(res)
                                if (s.code == 1) {
                                    layer.alert("添加成功");
                                    setTimeout(function () {
                                        location.reload();
                                    }, 2000);
                                }
                                else {
                                    layer.alert("添加失败");
                                }
                            }
                        })
                        return false; // 阻止默认 form 跳转
                    });
                }
            });


            // 获取当前日期时间
            var now = new Date();
            var year = now.getFullYear();
            var month = ("0" + (now.getMonth() + 1)).slice(-2);
            var day = ("0" + now.getDate()).slice(-2);
            var hours = ("0" + now.getHours()).slice(-2);
            var minutes = ("0" + now.getMinutes()).slice(-2);
            var seconds = ("0" + now.getSeconds()).slice(-2);
            var serialNumber = year + month + day + hours + minutes + seconds;
            var inputElement = document.getElementById('financeTypeNo');
            inputElement.value = serialNumber;
            console.log(inputElement.value)



        }
    })

    // 定义编辑数据的函数（实现反填及修改提交等逻辑）
    window.editData = function (id) {
        // 先根据id获取要编辑的数据，发起Ajax请求
        $.ajax({
            type: "GET",
            url: "../Purchase/GetFinanceTypeModel",  // 替换为实际的后台根据id获取数据的接口地址
            data: { id: id, token: localStorage.getItem("token") },
            success: function (res) {
                var res = JSON.parse(res)
                console.log(res)
                $(res.data).each(function () {
                    $('#financeTypeId').val(this.financeTypeId)
                    $('#financeTypeNo').val(this.financeTypeNo)
                    $('#financeTypeNames').val(this.financeTypeName)
                    $('#financeTyperemark').val(this.financeTyperemark)
                    $('#office_id').val(this.office_id)
                    $('#user_id').val(this.user_id)
                    $('#createName').val(this.createName)
                    $('#createTime').val(this.createTime)
                    $('#updateName').val(this.updateName)
                    $('#updateTime').val(this.updateTime)

                    obj.financeTypeId = this.financeTypeId
                    obj.financeTypeNo = this.financeTypeNo
                    obj.financeTypeName = this.financeTypeName
                    obj.financeTyperemark = this.financeTyperemark
                    obj.office_id = this.office_id
                    obj.user_id = this.user_id
                    obj.createName = this.createName
                    obj.createTime = this.createTime
                    obj.updateName = '张三'
                    obj.updateTime = '2024-11-22'
                    obj.isdelete=false

                })
            },
        });

        layer.open({
            type: 1,
            title: '编辑财务类别',
            content: `
                          <form class="layui-form" action="">
              <div class="layui-form-item">
                <div class="layui-inline">
                  <label class="layui-form-label">类别编号</label>
                  <div class="layui-input-block">
                    <input type="text" name="financeTypeNo" id="financeTypeNo" autocomplete="off" class="layui-input">
                  </div>
                </div>
                <div class="layui-inline">
                  <label class="layui-form-label">类别名称</label>
                  <div class="layui-input-block">
                        <input type="text" name="financeTypeName" id="financeTypeNames" autocomplete="off" class="layui-input">
                  </div>
                </div>
              </div>
              <div class="layui-form-item layui-form-text">
                <label class="layui-form-label">备注</label>
                <div class="layui-input-block">
                          <textarea placeholder="请输入内容" name="financeTyperemark" id="financeTyperemark" class="layui-textarea"></textarea>
                </div>
              </div>
              <div class="layui-form-item" style="text-align:center">
                    <button class="layui-btn" lay-submit lay-filter="demo-login">确认</button>
                <button type="reset" class="layui-btn layui-btn-primary">取消</button>
              </div>
            </form>
                    `,
            area: ['700px', '400px'],
            success: function () {
                var obj1 = {
                    financeTypeId: '',
                    financeTypeNo: '',
                    financeTypeName: '',
                    financeTyperemark: '',
                    office_id: '',
                    user_id: '',
                    createName: '',
                    createTime: '',
                    updateName: '',
                    updateTime: '',
                    isdelete:'',
                };
                // 对弹层中的表单进行初始化渲染
                form.render();
                // 表单提交事件
                form.on('submit(demo-login)', function (data) {
                    var field = data.field;
                    obj1.financeTypeId = obj.financeTypeId
                    obj1.financeTypeNo = field.financeTypeNo
                    obj1.financeTypeName = field.financeTypeName
                    obj1.financeTyperemark = field.financeTyperemark
                    obj1.office_id = obj.office_id
                    obj1.userid = obj.userid
                    obj1.user_id = obj.user_id
                    obj1.createTime = obj.createTime
                    obj1.updateName = '张三'
                    obj1.updateTime = '2024-11-22'
                    obj1.isdelete=false
                    $.ajax({
                        url: '../Purchase/GetFinanceTypeUpd',
                        type: 'post',
                        data: { obj1, token: localStorage.getItem("token") },
                        success: function (res) {
                            var res = JSON.parse(res)
                            console.log(field)
                            console.log(res)
                            if (res.code == 1) {
                                layer.alert("修改成功");
                                setTimeout(function () {
                                    location.reload();
                                }, 2000);
                            }
                            else {
                                layer.alert("修改失败");
                            }
                        }
                    })
                    return false; // 阻止默认 form 跳转
                });
            }
        });
    };

    // 点击编辑按钮的事件处理
    $('#batchUpdBtn').click(function () {
        var checkStatus = table.checkStatus('financeTypetable');
        var selectedIds = checkStatus.data.map(function (item) { return item.financeTypeId; });
        console.log(selectedIds[0])
        if (selectedIds.length === 0) {
            layer.msg('请选择一条要编辑的数据', { icon: 2 });
            return;
        }

        editData(selectedIds[0]);
    });




    // 点击批量删除按钮的事件处理
    $('#batchDeleteBtn').click(function () {
        var checkStatus = table.checkStatus('financeTypetable');
        var selectedIds = checkStatus.data.map(function (item) { return item.financeTypeId; });
        console.log(selectedIds)
        if (selectedIds.length === 0) {
            layer.msg('请至少选择一条要删除的数据', { icon: 2 });
            return;
        }
        layer.confirm('确定要批量删除选中的 ' + selectedIds.length + ' 条数据吗？', function (index) {
            // 发送Ajax请求到后端，传递选中的id数组进行删除操作
            $.ajax({
                url: '../Purchase/GetFinanceDelRange', // 后端批量删除接口地址，根据实际调整
                type: 'POST',
                data: { ids: JSON.stringify(selectedIds), token: localStorage.getItem("token") },
                success: function (res) {
                    var res = JSON.parse(res)
                    console.log(res)
                    if (res.code > 0) {
                        layer.msg('批量删除成功', { icon: 1 });
                        Show()
                    } else {
                        layer.msg('批量删除失败：' + res.message, { icon: 2 });
                    }
                    layer.close(index);
                },
                error: function () {
                    layer.msg('请求出错，请稍后再试', { icon: 2 });
                    layer.close(index);
                }
            });
        });
    });

   
})

$(function () {
    Show()
})
function refesh() {
    location.reload();
}
//显示
function Show() {
    layui.use(['form', 'table'], function () {
        var table = layui.table;
        var financeTypeName = $("#financeTypeName").val();

        $.ajax({
            url: '/Purchase/GetFinanceTypeShow',
            type: "get",
            data: {
                financeTypeName: financeTypeName,
                token: localStorage.getItem("token"),
            },
            success: function (data) {
                data = JSON.parse(data);
                console.log(data.data);
                if (data.code == 0) {
                    table.render({
                        elem: financeTypetable,
                        data: data.data,
                        toolbar: '#toolbarDemo',
                        defaultToolbar: ['exports'],
                        cols: [[
                            { type: 'checkbox', fixed: 'left' },
                            { field: 'financeTypeNo', title: '类别编号' },
                            { field: 'financeTypeName', title: '类别名称' },
                            { field: 'createTime', title: '创建时间', templet: function (d) {
                                return formatTime(d.createTime); // 调用自定义的时间格式转换函数
                            } },
                            {
                                field: '', title: '操作', templet: function (d) {
                                    return '<a class="layui-btn layui-btn-edit layui-btn-xs" onclick="editData(' + d.financeTypeId + ')"><i class="layui-icon layui-icon-edit"></i>编辑</a> ' +
                                        '<a class="layui-btn layui-btn-danger layui-btn-xs" onclick="deleteData(' + d.financeTypeId + ')"><i class="layui-icon layui-icon-delete"></i>删除</a>';
                                }
                            }
                        ]],
                    });
                } else {
                    console.log(res.msg)
                }
            },
            error: function () {
                console.log("请求失败")
            }
        });
    });
}
// 定义删除数据的函数（此处简单示意，可参考之前详细的删除功能代码完善）
window.deleteData = function (id) {
    layer.confirm('确定要删除该条数据吗？', function (index) {
        $.ajax({
            type: "Post",
            url: "../Purchase/GetFinanceDel",  // 替换为实际的后台删除数据接口地址
            data: { data: JSON.stringify({ financeTypeId: id }), token: localStorage.getItem("token") },
            success: function (res) {
                var res = JSON.parse(res)
                if (res.code === 1) {
                    layer.alert("删除成功");
                    Show();  // 重新加载数据，刷新表格显示
                } else {
                    layer.alert("删除失败");

                }
            },
            error: function () {
                layer.msg('删除失败，请稍后重试', {
                    time: 2000,
                    icon: 2
                });
            }
        });
        layer.close(index);
    });
};
// 定义时间格式转换函数
function formatTime(timeStamp) {
    if (timeStamp) {
        var date = new Date(timeStamp);
        var year = date.getFullYear();
        var month = ('0' + (date.getMonth() + 1)).slice(-2);
        var day = ('0' + date.getDate()).slice(-2);
        var hour = ('0' + date.getHours()).slice(-2);
        var minute = ('0' + date.getMinutes()).slice(-2);
        var second = ('0' + date.getSeconds()).slice(-2);
        return year + '-' + month + '-' + day + ' ' + hour + ':' + minute + ':' + second;
    }
    return "";
}